package com.best4cloud.user.web.rest;

import com.best4cloud.common.core.result.Result;
import com.best4cloud.user.domain.SysMenu;
import com.best4cloud.user.domain.SysRole;
import com.best4cloud.user.domain.SysUser;
import com.best4cloud.user.service.SysUserService;
import com.best4cloud.user.web.rest.request.SysLoginQuery;
import com.best4cloud.user.web.rest.response.SysLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

@Api(tags = "系统用户资源")
@Slf4j
@RestController
@RequestMapping("/api/sys/user")
@AllArgsConstructor
public class SysUserResource {

    private final SysUserService sysUserService;

    @ApiOperation(value = "login", notes = "登录")
    @PostMapping("/login")
    public Result<SysLoginVO> login(@RequestBody @Validated SysLoginQuery loginDTO) {
        SysLoginVO sysLoginVO = new SysLoginVO();
        SysUser sysUser = sysUserService.login(loginDTO);
        Set<String> roleCodes = sysUser.getRoles()
                .stream()
                .map(SysRole::getRoleCode)
                .collect(Collectors.toSet());
        Set<String> permissions = sysUser.getRoles()
                .stream()
                .map(SysRole::getMenus)
                .flatMap(Collection::stream)
                .map(SysMenu::getPermission)
                .collect(Collectors.toSet());
        sysLoginVO.setUsername(sysUser.getUsername());
        sysLoginVO.setRoleCodes(roleCodes);
        sysLoginVO.setPermissions(permissions);
        return Result.success(sysLoginVO);
    }

}
